import 'dart:math';
import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/events.dart';
import 'package:flutter/material.dart';

import 'GameBuild.dart';

// 方块类型枚举
enum TileType {
  red,
  green,
  blue,
  yellow,
  purple;

  static TileType random() {
    return TileType.values[Random().nextInt(TileType.values.length)];
  }

  String get imagePath {
    switch (this) {
      case TileType.red:
        return 'cat1.jpg';
      case TileType.green:
        return 'cat2.jpg';
      case TileType.blue:
        return 'cat3.jpg';
      case TileType.yellow:
        return 'cat4.jpg';
      case TileType.purple:
        return 'cat5.jpg';
    }
  }
}

class Tile extends SpriteComponent with TapCallbacks {
  final TileType type;
  int row;
  int col;
  bool isSelected = false;
  bool _imageLoadFailed = false;
  final Radius cornerRadius = const Radius.circular(8);

  Tile({
    required this.type,
    required super.position,
    required super.size,
    required this.row,
    required this.col,
  });

  @override
  Future<void> onLoad() async {
    super.onLoad();
    anchor = Anchor.topLeft;
    
    try {
      // 加载贴图
      sprite = await Sprite.load(type.imagePath);
      print('成功加载贴图: ${type.imagePath}');
    } catch (e) {
      print('加载贴图失败: ${type.imagePath}, 错误: $e');
      // 标记贴图加载失败
      _imageLoadFailed = true;
    }
  }

  @override
  void render(Canvas canvas) {
    // 创建圆角矩形路径用于裁剪
    final rect = Rect.fromLTWH(0, 0, width, height);
    final rrect = RRect.fromRectAndRadius(rect, cornerRadius);
    final clipPath = Path()..addRRect(rrect);
    
    // 保存画布状态
    canvas.save();
    
    // 应用裁剪区域
    canvas.clipPath(clipPath);
    
    // 绘制贴图或纯色
    if (!_imageLoadFailed && sprite != null && sprite!.image != null) {
      // 计算缩放比例以保持宽高比并填满整个区域
      final srcWidth = sprite!.src.width;
      final srcHeight = sprite!.src.height;
      
      // 计算宽度和高度的缩放因子
      final scaleX = width / srcWidth;
      final scaleY = height / srcHeight;
      
      // 选择较大的缩放因子以确保填满整个区域
      final scale = max(scaleX, scaleY);
      
      // 计算绘制区域，使其居中
      final drawWidth = srcWidth * scale;
      final drawHeight = srcHeight * scale;
      final dx = (width - drawWidth) / 2;
      final dy = (height - drawHeight) / 2;
      
      // 绘制图片
      canvas.drawImageRect(
        sprite!.image,
        sprite!.src,
        Rect.fromLTWH(dx, dy, drawWidth, drawHeight),
        Paint()..filterQuality = FilterQuality.high,
      );
    } else {
      // 如果没有贴图，绘制纯色方块
      final paint = Paint()
        ..color = getColorByType(type)
        ..style = PaintingStyle.fill;

      canvas.drawRect(rect, paint);
    }
    
    // 恢复画布状态
    canvas.restore();

    // 如果被选中，绘制边框
    if (isSelected) {
      final borderPaint = Paint()
        ..color = Colors.white
        ..style = PaintingStyle.stroke
        ..strokeWidth = 3;

      canvas.drawRRect(rrect, borderPaint);
    }
  }

  Color getColorByType(TileType type) {
    switch (type) {
      case TileType.red:
        return Colors.red;
      case TileType.green:
        return Colors.green;
      case TileType.blue:
        return Colors.blue;
      case TileType.yellow:
        return Colors.yellow;
      case TileType.purple:
        return Colors.purple;
    }
  }

  @override
  void onTapDown(TapDownEvent event) {
    super.onTapDown(event);

    // 通知游戏板这个方块被点击了
    final gameBoard = parent as GameBoard;
    gameBoard.onTileSelected(this);
  }
}